package com.setoption.service;

import com.setoption.enums.ExceptionEnums;
import com.setoption.exception.MyException;
import com.setoption.mapper.InfoManagersMapper;
import com.setoption.pojo.*;
import com.setoption.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class InfoManagerService {
    @Autowired
    private JwtUtil jwtUtil;
    @Resource
    private InfoManagersMapper managersMapper;


    public Managers selectManager(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token==null || "".equals(token)) {
            throw new MyException(ExceptionEnums.NO_PERMISSIONS);
        }
        Claims claims ;
        try {
            claims = jwtUtil.parseJWT(token);
        } catch (Exception e) {
            throw new MyException(ExceptionEnums.TOKEN_TIME_OUT);
        }
        Example example = new Example(Managers.class);
        example.createCriteria().andEqualTo("managerNo",Integer.parseInt(claims.getId()));
        example.excludeProperties("managerPassword");
        List<Managers> managers = managersMapper.selectByExample(example);
        return managers.get(0);
    }

    public int setManagerInfo(Map<String, Object> map){
        String password=String.valueOf(map.get("manager_password"));
        String phone=String.valueOf(map.get("manager_phone"));
        Managers managers=new Managers();
        Integer id=Integer.parseInt( map.get("id").toString());
        managers.setId(id);
        managers.setManagerPassword(password);
        managers.setManagerPhone(phone);
        int result=managersMapper.updateByPrimaryKeySelective(managers);
        if(result==0){
            throw new MyException(ExceptionEnums.TABLE_SET_ERROR);
        }
        return result;
    }
}
